import 'package:elephant_fish/TRTCChatSalonDemo/model/TRTCChatSalon.dart';
import 'package:elephant_fish/TRTCChatSalonDemo/model/TRTCChatSalonDef.dart';
import 'package:elephant_fish/TRTCChatSalonDemo/ui/room/VoiceRoomPage.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/add_nocite_request.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/close_voice_request.dart';
import 'package:elephant_fish/http/request/notice_list_request.dart';
import 'package:elephant_fish/http/request/open_voice_request.dart';
import 'package:elephant_fish/http/request/voice_set_join_level_request.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/model/voice_notice.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'login_page.dart';

class VoiceSettingPage extends StatefulWidget {
  final UserInfoEntity userInfoEntity;
  const VoiceSettingPage({Key key, this.userInfoEntity}) : super(key: key);

  @override
  _VoiceSettingPageState createState() => _VoiceSettingPageState();
}

class _VoiceSettingPageState extends State<VoiceSettingPage> {

  VoiceNotice voiceNotice;
  String content ;
  bool _switchValueEffect = false;
  TRTCChatSalon trtcVoiceRoom;
  int _dropValue = 0;
  TextEditingController noticeController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    getNotice();
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        leading: GestureDetector(
          child: Icon(
            Icons.arrow_back_ios,
            size: SizeUtil.px(32),
            color: Color(0xffffffff),
          ),
          onTap: () {
            Navigator.pop(context);
          },
        ),
        title: Text(
          '语音房设置',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xffffffff)),
        ),
      ),
      body: Column(
        children: [
          Container(
            width: double.infinity,
            height: 55,
            color: Color(0xff2b244d),
            child: Row(
              children: [
                SizedBox(width: 15.5,),
                Text('开启/关闭语音房',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14.5),),
                SizedBox(width: 187,),
                CupertinoSwitch(
                  activeColor: Color(0xff66dca2),
                  trackColor: Color(0xfff1f1f1),
                  value: _switchValueEffect,
                  // 点击或者拖拽事件
                  onChanged: (value){
                    _switchValueEffect = value;
                    setState(() {
                      if(_switchValueEffect){
                        openRoom();
                      }else{
                        closeRoom();
                      }

                    });
                  },
                ),
              ],
            ),
          ),
          SizedBox(height: 20,),
          Container(
            width: double.infinity,
            height: 55,
            color: Color(0xff2b244d),
            child: Row(
              children: [
                SizedBox(width: 15.5,),
                Text('直播公告',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14.5),),
                SizedBox(width: 200,),
                InkWell(
                  child:Text(content == null ? '未设置' :content,style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14.5),),
                  onTap: (){
                    _showNotice();
                  },
                )

              ],
            ),
          ),
          Container(
            width: double.infinity,
            height: 55,
            color: Color(0xff2b244d),
            child: Row(
              children: [
                SizedBox(width: 15.5,),
                Text('进入语音房权限',style: TextStyle(color: Color(0xfff3f3f3),fontSize: 14.5),),
                SizedBox(width: 120,),
                DropdownButton(
                  value: _dropValue,
                  items: [
                    DropdownMenuItem(child: Text('无进入等级限制',style: TextStyle(fontSize: 14.5),),value: 0,),
                    DropdownMenuItem(child: Text('限制等级10级进入',style: TextStyle(fontSize: 14.5)),value: 1),
                    DropdownMenuItem(child: Text('限制等级20级进入',style: TextStyle(fontSize: 14.5)),value: 2),
                    DropdownMenuItem(child: Text('限制等级30级进入',style: TextStyle(fontSize: 14.5)),value: 3),
                    DropdownMenuItem(child: Text('限制等级40级进入',style: TextStyle(fontSize: 14.5)),value: 4),
                    DropdownMenuItem(child: Text('限制等级50级进入',style: TextStyle(fontSize: 14.5)),value: 5),
                    DropdownMenuItem(child: Text('限制等级60级进入',style: TextStyle(fontSize: 14.5)),value: 6),
                    DropdownMenuItem(child: Text('限制等级70级进入',style: TextStyle(fontSize: 14.5)),value: 7),
                    DropdownMenuItem(child: Text('限制等级80级进入',style: TextStyle(fontSize: 14.5)),value: 8),
                    DropdownMenuItem(child: Text('限制等级90级进入',style: TextStyle(fontSize: 14.5)),value: 9),
                    DropdownMenuItem(child: Text('限制等级100级进入',style: TextStyle(fontSize: 14.5)),value: 10),
                    DropdownMenuItem(child: Text('限制等级110级进入',style: TextStyle(fontSize: 14.5)),value: 11),

                  ],style: TextStyle(color: Colors.grey),focusColor:Color(0xff140c3d),underline: Container(),onChanged: (value){
                  setState(() {
                    _dropValue = value;
                    setJoinLevel(_dropValue * 10);
                  });
                },)
              ],
            ),
          ),
          SizedBox(height: 400,),
          InkWell(
            child: Container(
              width: 325,
              height: 45.5,
              decoration: BoxDecoration(
                color: Color(0xffe62d6c),
                borderRadius: BorderRadius.all(Radius.circular(23))
              ),
              child: Center(
                child: Text('进入我的语音房',style: TextStyle(color: Color(0xfff9f9f9),fontSize: 16),),
              ),
            ),
            onTap: (){
              RoomInfo roomInfo = RoomInfo(roomId: widget.userInfoEntity.noticeRoom,roomName:  widget.userInfoEntity.nickname,coverUrl: widget.userInfoEntity.avatar,memberCount: 1,ownerId: widget.userInfoEntity.userId,ownerName: widget.userInfoEntity.nickname);
              goRoomInfoPage(roomInfo);
            },
          )
        ],
      ),
    );
  }

  void _showNotice() {
    final top = 12.0;
    final txBottom = 40.0;
    final txHeight = 100.0;
    TextEditingController nameController = TextEditingController();
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return StatefulBuilder(builder: (ctx2, state) {
          return Container(
            height: MediaQuery.of(ctx2).viewInsets.bottom +
                txHeight +
                top +
                txBottom,
            color: Colors.white,
            child: Stack(
              children: <Widget>[
                Positioned(
                    left: 12,
                    bottom: (MediaQuery.of(ctx2).viewInsets.bottom < 0)
                        ? 0
                        : MediaQuery.of(ctx2).viewInsets.bottom,
                    right: 0,
                    top: top,
                    child: Container(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: <Widget>[
                              Expanded(
                                  child: Container(
                                    padding: EdgeInsets.all(8),
                                    height: txHeight,
                                    color: Color(0xfff7f7f7),
                                    child: TextField(
                                      // scrollPadding: EdgeInsets.zero,
                                      controller: noticeController,
                                      autofocus: true,
                                      maxLines: 4,
                                      style: TextStyle(
                                          fontSize: 15, color: Colors.black),
                                      decoration: InputDecoration(
                                          contentPadding: EdgeInsets.zero,
                                          isDense: true,
                                          border: InputBorder.none),
                                    ),
                                  )),
                              InkWell(
                                child: Container(
                                  padding: EdgeInsets.only(left: 12, right: 12),
                                  child: Text("确定",
                                      style: TextStyle(
                                          fontSize: 15,
                                          color: Color(0xffe62d6c))),
                                ),
                                onTap: () {
                                  setState(() {
                                    content = noticeController.text;
                                    editNotice();
                                  });
                                  Navigator.pop(context);
                                },
                              )
                            ],
                          ),
                        ],
                      ),
                    ))
              ],
            ),
          );
        });
      },
    );
  }

  Future<void> getNotice() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = NoticeListRequest();
    request.add('room_id', widget.userInfoEntity.noticeRoom).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }else if (result['code'] == 0){
      trtcVoiceRoom = await TRTCChatSalon.sharedInstance();
      List<Map<String, dynamic>>  list = List();
      setState(() {
        widget.userInfoEntity.noticeStatus == 1 ?_switchValueEffect = true : _switchValueEffect = false;
        list = List<Map<String, dynamic>>.from(result['data']);
        if(list.length > 0){
          voiceNotice = VoiceNotice.fromJson(list[0]);
          content = voiceNotice.content;

        }

      });
    }
  }

  Future<void> editNotice() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AddNoticeRequest();
    request.add('type', 2).add('room_id', widget.userInfoEntity.noticeRoom).add('content', noticeController.text).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }else if (result['code'] == 0){
     TxUtils.showToast(result['data'], context);
    }
  }

  Future<void> closeRoom() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = CloseVoiceRequest();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }else if (result['code'] == 0){
      _switchValueEffect = false;
      TxUtils.showToast(result['data'], context);
    }
  }

  Future<void> openRoom() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = OpenVoiceRequest();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }else if (result['code'] == 0){
      _switchValueEffect = true;
      TxUtils.showToast(result['data'], context);
    }
  }

  goRoomInfoPage(RoomInfo roomInfo) async {
    String loginUserId = await TxUtils.getLoginUserId();
    if (roomInfo.ownerId.toString() == loginUserId) {
      await trtcVoiceRoom.setSelfProfile(
        roomInfo.ownerName,
        'http://119.28.131.94:82' + roomInfo.coverUrl,
      );
      await TxUtils.setStorageByKey("loginUserName",roomInfo.ownerName);
      String ownerId = await TxUtils.getLoginUserId();
      Navigator.popAndPushNamed(
        context,
        "/chatSalon/roomAnchor",
        arguments: {
          "coverUrl": 'http://119.28.131.94:82' + roomInfo.coverUrl,
          "roomName":  roomInfo.ownerName,
          "roomId": roomInfo.roomId,
          "ownerId": roomInfo.ownerId,
          'isNeedCreateRoom': true,
        },
      );
      // Navigator.pushReplacementNamed(
      //   context,
      //   "/chatSalon/roomAudience",
      //   arguments: {
      //     'roomId': roomInfo.roomId,
      //     "ownerId": roomInfo.ownerId,
      //     "roomName": roomInfo.roomName,
      //     'isNeedCreateRoom': false,
      //   },
      // );
      return;
    }
    Navigator.pushReplacementNamed(
      context,
      "/chatSalon/roomAudience",
      arguments: {
        "ownerId": roomInfo.ownerId,
        "roomName": roomInfo.roomName,
        'roomId': roomInfo.roomId,
        'isNeedCreateRoom': false,
      },
    );
  }

  ///设置语音房进入等级
  Future<void> setJoinLevel(int i) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = VoiceSetJoinLevelRequest();
    request.add('room_id', widget.userInfoEntity.noticeRoom).add('level', i).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }else if (result['code'] == 0){
      TxUtils.showToast(result['data'], context);
    }
  }
}
